package com.lmc.base.demo.ai.controller;

import com.alibaba.cloud.ai.tongyi.chat.TongYiChatModel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.image.Image;
import org.springframework.ai.image.ImageMessage;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;

/**
 * @author lmc
 * @Description: TODO
 * @Create 2024-08-09 22:58
 * @version: 1.0
 */
@RestController
@RequestMapping("/image")
@Slf4j
public class ImageController {

    /**
     * 文本生成图片Client
     */
    @Resource
    private TongYiImagesClient imagesClient;


    @RequestMapping("/create")
    public String image(String message) {
        // 封装信息
        ImageMessage imageMessage = new ImageMessage(message);
        // 创建Prompt
        ImagePrompt imagePrompt = new ImagePrompt(Collections.singletonList(imageMessage));
        // 调用文本生成图片Client
        Image output = imagesClient.call(imagePrompt).getResult().getOutput();
        // 生成图片URL
        return output.getUrl();
    }

    /**
     * 调用自定义函数回答用户的提问
     *
     * @param prompt       用户的提问
     * @param functionName 函数名称（bean的名称，类名小写）
     * @return SSE流式响应
     */
//    @GetMapping(value = "chat/stream/function", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<ServerSentEvent<String>> chatStreamWithFunction(@RequestParam String prompt, @RequestParam String functionName) {
//        return ChatClient.create(dashScopeAiChatModel).prompt()
//                .messages(new UserMessage(prompt))
//                // spring ai会从已注册为bean的function中查找函数，将它添加到请求中。如果成功触发就会调用函数
//                .functions(functionName)
//                .stream()
//                .chatResponse()
//                .map(chatResponse -> ServerSentEvent.builder(toJson(chatResponse))
//                        .event("message")
//                        .build());
//    }

}
